import 'package:efood_multivendor/controller/auth_controller.dart';
import 'package:efood_multivendor/controller/category_controller.dart';
import 'package:efood_multivendor/controller/localization_controller.dart';
import 'package:efood_multivendor/controller/splash_controller.dart';
import 'package:efood_multivendor/controller/user_controller.dart';
import 'package:efood_multivendor/data/model/response/response_model.dart';
import 'package:efood_multivendor/data/model/response/userinfo_model.dart';
import 'package:efood_multivendor/helper/route_helper.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/custom_button.dart';
import 'package:efood_multivendor/view/base/custom_snackbar.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:dropdown_button2/dropdown_button2.dart';

class AgeDialog extends StatefulWidget {
  final Function()? callback;

  AgeDialog({Key? key, this.callback}) : super(key: key);
  @override
  State<AgeDialog> createState() => _AgeDialogState();
}

class _AgeDialogState extends State<AgeDialog> {
  bool isChecked = false;
  List<int> years = [];
  List<String> months = [];
  List<int> days = [];
  String? currentYear;
  String? currentMonth;
  String? currentDay;
  int? selectedLanguage;
  bool isLoading = false;

  static const int MaxAge = 100;
  static const int MaxMonth = 31;
  static const int YearInHour = 8760;

  @override
  void initState() {
    selectedLanguage = Get.find<LocalizationController>().selectedIndex;
    months = selectedLanguage == 0
        ? [
            "Jan",
            "Feb",
            "Mar",
            "Apr",
            "May",
            "Jun",
            "Jul",
            "Aug",
            "Sep",
            "Oct",
            "Nov",
            "Dec"
          ]
        : selectedLanguage == 1
            ? [
                "መስከረም",
                "ጥቅምት",
                "ህዳር",
                "ታህሳስ",
                "ጥር",
                "የካቲት",
                "መጋቢት",
                "ሚይዚያ",
                "ግንቦት",
                "ሰኔ",
                "ሐምሌ",
                "ነሐሴ",
                "ጳጉሜ"
              ]
            : [
                "一 月",
                "二 月",
                "三 月",
                "四 月",
                "五 月",
                "六 月",
                "七 月",
                "八 月",
                "九 月",
                "十 月",
                "十一 月",
                "十二 月"
              ];

    for (int i = 0; i < MaxAge; i++) {
      years.add(DateTime.now().year - i);
    }

    for (int i = 1; i <= MaxMonth; i++) {
      days.add(i);
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      backgroundColor: Theme.of(context).cardColor,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(20),
      ),
      title: SizedBox(),
      content: Container(
          width: 250,
          height: 230,
          decoration: BoxDecoration(
            color: const Color(0xffffffff),
            borderRadius: BorderRadius.circular(28.0),
          ),
          child: Center(
              child: Column(
            children: [
              Text(
                "birthdate".tr,
                style: sfRegular,
              ),
              SizedBox(
                height: 5,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    height: 30,
                    width: 70,
                    child: Row(
                      children: [
                        Expanded(
                          child: DropdownButtonFormField2(
                            // dropdownMaxHeight: 100,
                            // itemHeight: 25,
                            value: currentYear ?? null,
                            hint: Text(
                              'year'.tr,
                              style: sfRegular.copyWith(
                                  fontSize: Dimensions.fontSizeSmall),
                            ),
                            decoration: const InputDecoration(
                              contentPadding: EdgeInsets.symmetric(
                                  vertical: 0, horizontal: 5),
                              constraints: BoxConstraints(maxWidth: 10),
                              enabledBorder: OutlineInputBorder(
                                  borderSide: const BorderSide(
                                      color: Colors.deepOrange),
                                  borderRadius: BorderRadius.zero),
                              border: OutlineInputBorder(),
                            ),
                            //  icon: const Icon(Icons.arrow_drop_down),
                            items: years.map((int item) {
                              return DropdownMenuItem(
                                value: item.toString(),
                                child: Container(
                                  margin: const EdgeInsets.all(0.0),
                                  padding: const EdgeInsets.all(0),
                                  child: Text(
                                    item.toString(),
                                    softWrap: true,
                                    style: sfRegular.copyWith(
                                        fontSize: Dimensions.fontSizeSmall),
                                  ),
                                ),
                              );
                            }).toList(),
                            onChanged: (newValue) {
                              setState(() {
                                currentYear = newValue;
                              });
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(
                    width: 2,
                  ),
                  Container(
                    height: 30,
                    width: 83,
                    child: Row(
                      children: [
                        Expanded(
                          child: DropdownButtonFormField2(
                            // dropdownMaxHeight: 100,
                            // itemHeight: 25,
                            isExpanded: true,
                            value: currentMonth ?? null,
                            hint: Text(
                              'month'.tr,
                              style: sfRegular.copyWith(
                                  fontSize: Dimensions.fontSizeSmall),
                            ),
                            decoration: const InputDecoration(
                              contentPadding: EdgeInsets.symmetric(
                                  vertical: 0, horizontal: 5),
                              constraints: BoxConstraints(maxWidth: 10),
                              enabledBorder: OutlineInputBorder(
                                  borderSide: const BorderSide(
                                      color: Colors.deepOrange),
                                  borderRadius: BorderRadius.zero),
                              border: OutlineInputBorder(),
                            ),
                            //   icon: const Icon(Icons.arrow_drop_down),
                            items: months.map((String item) {
                              return DropdownMenuItem(
                                value: item.toString(),
                                child: Text(
                                  item.toString(),
                                  style: sfRegular.copyWith(
                                      fontSize: Dimensions.fontSizeSmall),
                                ),
                              );
                            }).toList(),
                            onChanged: (newValue) {
                              setState(() {
                                currentMonth = newValue;
                              });
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(
                    width: 2,
                  ),
                  Container(
                    height: 30,
                    width: 55,
                    child: Row(
                      children: [
                        Expanded(
                          child: DropdownButtonFormField2(
                            isExpanded: true,
                            value: currentDay ?? null,
                            hint: Text(
                              'day'.tr,
                              style: sfRegular.copyWith(
                                  fontSize: Dimensions.fontSizeSmall),
                            ),
                            decoration: const InputDecoration(
                              contentPadding: EdgeInsets.symmetric(
                                  vertical: 0, horizontal: 5),
                              constraints: BoxConstraints(maxWidth: 10),
                              enabledBorder: OutlineInputBorder(
                                  borderSide: const BorderSide(
                                      color: Colors.deepOrange),
                                  borderRadius: BorderRadius.zero),
                              border: OutlineInputBorder(),
                            ),
                            //  icon: const Icon(Icons.arrow_drop_down),
                            items: days.map((int item) {
                              return DropdownMenuItem(
                                value: item.toString(),
                                child: Text(
                                  item.toString(),
                                  style: sfRegular.copyWith(
                                      fontSize: Dimensions.fontSizeSmall),
                                ),
                              );
                            }).toList(),
                            onChanged: (newValue) {
                              setState(() {
                                currentDay = newValue;
                              });
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              SizedBox(height: 8),
              Text(
                "age_policy".tr,
                style: sfRegular.copyWith(fontSize: Dimensions.fontSizeSmall),
                textAlign: TextAlign.start,
              ),
              Row(
                children: [
                  Checkbox(
                      activeColor: Colors.deepOrange,
                      value: isChecked,
                      onChanged: (checked) {
                        setState(() {
                          isChecked = checked ?? false;
                        });
                      }),
                  SizedBox(width: 5),
                  Expanded(
                    child: Text(
                      "agreement".tr,
                      style: sfRegular.copyWith(
                          fontSize: Dimensions.fontSizeSmall),
                    ),
                  ),
                ],
              ),
              SizedBox(height: 10),
              !isLoading
                  ? CustomButton(
                      buttonText: 'continue'.tr,
                      width: 100,
                      onPressed: () async {
                        if (isChecked &&
                            currentMonth != null &&
                            currentYear != null &&
                            currentDay != null) {
                          setState(() {
                            isLoading = true;
                          });
                          int month = months.indexOf(currentMonth!) == 12
                              ? months.indexOf(currentMonth!)
                              : months.indexOf(currentMonth!) + 1;
                          String dateOfBirth =
                              "${int.parse(currentYear!)}-$month-${int.parse(currentDay!)}";

                          UserInfoModel _updatedUser = UserInfoModel(
                              fName: Get.find<UserController>()
                                  .userInfoModel
                                  ?.fName,
                              birthDate: dateOfBirth);
                          ResponseModel _responseModel =
                              await Get.find<UserController>().updateUserInfo(
                                  _updatedUser,
                                  Get.find<AuthController>().getUserToken());

                          if (_responseModel.isSuccess) {
                            if ((DateTime.now()
                                        .difference(DateTime(
                                            int.parse(currentYear!),
                                            months.indexOf(currentMonth!) == 12
                                                ? months.indexOf(currentMonth!)
                                                : months.indexOf(
                                                        currentMonth!) +
                                                    1,
                                            int.parse(currentDay!)))
                                        .inHours /
                                    YearInHour) >=
                                21) {
                              Navigator.of(context).pop();
                              widget.callback?.call();
                            } else {
                              Navigator.of(context).pop();
                              showRestrictionDialog(context);
                            }
                          } else {
                            showCustomSnackBar(_responseModel.message);
                          }
                          setState(() {
                            isLoading = false;
                          });
                        }
                      },
                    )
                  : Center(
                      child: CircularProgressIndicator.adaptive(
                        backgroundColor:
                            Theme.of(context).colorScheme.secondary,
                      ),
                    ),
            ],
          ))),
    );
  }

  static void showRestrictionDialog(BuildContext context) {
    AlertDialog rDialog = AlertDialog(
        backgroundColor: Theme.of(context).cardColor,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20),
        ),
        title: SizedBox(),
        content: Container(
          width: 250,
          height: 60,
          child: Center(
              child: Text(
            'restriction_msg'.tr,
            style: sfRegular,
            textAlign: TextAlign.center,
          )),
        ));

    Get.dialog(rDialog, barrierDismissible: true);
  }
}
